package team.bluepen.supermarket.web.listener;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.data.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 在线用户监听器
 * @author Kai
 */
@WebListener
public class UserLoginListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
    private static final List<User> ONLINE_USERS = new ArrayList<>();
    private ServletContext application = null;

    public static boolean isUserOnline(User user) {
        return ONLINE_USERS.contains(user);
    }

    public static List<User> getOnlineUsers() {
        return ONLINE_USERS;
    }


    public UserLoginListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        application = sce.getServletContext();

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        removeUser(se.getSession());
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        addUser(sbe.getSession());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        removeUser(sbe.getSession());
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {

    }

    private void addUser(HttpSession session) {
        if (session.getAttribute(Constant.SESSION_USER) == null) {
            return;
        }
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        if (isUserOnline(user)) {
            return;
        }
        ONLINE_USERS.add(user);
    }

    private void removeUser(HttpSession session) {
        if (session.getAttribute(Constant.SESSION_USER) == null) {
            return;
        }
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        if (!isUserOnline(user)) {
            return;
        }
        ONLINE_USERS.remove(user);
    }
}
